package com.zc.im.netty.start;

import com.zc.im.netty.handler.ChatServerInitializer;
import com.zc.im.util.ImGolbalTypeContext;
import com.zc.im.util.SpringContextUtils;
import com.zc.im.util.properties.NettyProperties;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.ImmediateEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.awt.*;
import java.net.InetSocketAddress;
import java.util.Properties;

@Component
public class ChatServer {

	private static Logger log = LoggerFactory.getLogger(ChatServer.class);

	private final ChannelGroup group = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);

	private final EventLoopGroup workerGroup = new NioEventLoopGroup();


	private Channel channel;
	private ChannelFuture start(InetSocketAddress address){
		ServerBootstrap boot = new ServerBootstrap();
		boot.group(workerGroup).channel(NioServerSocketChannel.class).childHandler(createInitializer(group));
		
		ChannelFuture f = boot.bind(address).syncUninterruptibly();
		channel = f.channel();
		return f;
	}

	protected ChannelHandler createInitializer(ChannelGroup group2) {
		return new ChatServerInitializer(group2);
	}

	private void destroy(){
		if(channel != null)
			channel.close();
		group.close();
		workerGroup.shutdownGracefully();
	}
	
	public static void startNettyServer() {
		final ChatServer server = new ChatServer();
		ChannelFuture f = server.start(
				new InetSocketAddress(ImGolbalTypeContext.propertiesMap.get(ImGolbalTypeContext.NETTY_HOST_NAME),
						Integer.parseInt(ImGolbalTypeContext.propertiesMap.get(ImGolbalTypeContext.NETTY_PORT))));
		log.info("Netty server start................");
		Runtime.getRuntime().addShutdownHook(new Thread(){
			@Override
			public void run() {
				server.destroy();
			}
		});
		f.channel().closeFuture().syncUninterruptibly();
	}
	
}
